package de.luisoft.web.servlet;

import java.io.IOException;
import java.nio.channels.IllegalSelectorException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.luisoft.dto.WahlDTO;
import de.luisoft.ui.model.ProjectModel;

public class CSVServlet extends AbstractListServlet {

	private static final Logger log = Logger.getLogger(CSVServlet.class.getName());

	private static final long serialVersionUID = 7161146165061872986L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		log.info("list user");

		resp.setContentType("text/csv");

		Map<String, ProjectModel> projectbyName = new LinkedHashMap<String, ProjectModel>();
		Map<String, List<WahlDTO>> t = getVotesByProject(projectbyName);

		Set<WahlDTO> allStudents = new HashSet<WahlDTO>();
		Set<WahlDTO> allAssignedStudents = new HashSet<WahlDTO>();
		
		int nbStudents2 = 0;
		//
		// Excel
		//
		try {
			// projects
			int i = 0;
			for (String p : t.keySet()) {
				List<WahlDTO> ws = t.get(p);
				allStudents.addAll(ws);

				resp.getWriter().append(";");
				resp.getWriter().append(p
						+ " ("
						+ ws.size() + "/" 
						+ projectbyName.get(p).getCapacity() + ")");
				i++;
			}
			resp.getWriter().append("\n");
			int nbStudents = allStudents.size();

			// assignments
			int j = 0; // row
			boolean found = true;
			while (found) {
				found = false;
				i = 0;
				resp.getWriter().append((j+1) + ";");
				for (String p : t.keySet()) {
					List<WahlDTO> ws = t.get(p);
					if (i > 0) resp.getWriter().append(";");

					if (j < ws.size()) {
						WahlDTO w = ws.get(j);
						resp.getWriter().append(w.getVorname() +" " + w.getName()
								+ " (" + w.getKlasse() + "," + w.getEmail() + ")");
						nbStudents2++;
						allStudents.remove(w);
						if (allAssignedStudents.contains(w)) {
							log.severe("Student " + w + " already assigned.");
							throw new IllegalStateException("Student " + w + " already assigned.");
						}
						allAssignedStudents.add(w);
						if (j < ws.size()-1) found = true;
					} else {
						resp.getWriter().append(" ");
					}
					i++;
				}
				j++;
				resp.getWriter().append("\n");
			}
			
			if (allStudents.size() > 0) {
				resp.getWriter().append("\n\nKeine Projektzuordnung für (" + allStudents.size()
					+ "/" + nbStudents + ") :"
					+ allStudents);
			} else {
				resp.getWriter().append("\n\nEs konnten alle " + nbStudents
						+ " Schüler zugeordnet werden.");
			}
			resp.getWriter().append("\n\nnbStudents2=" + nbStudents2 + "\n");

		} catch (Exception e) {
			e.printStackTrace();
			resp.getWriter().append(e.toString());
		}

		resp.getWriter().close();
	}
}
